Down casting & instanceof

상위 클래스로 형변환은 묵시적으로 이루어질 수 있다.
Down casting은 상위 클래스로 형변환된 클래스를 다시 원래 인스턴스 자료형으로 형 변환하는 것을 의미한다.
instanceof
ClassA instance 자료형A
ClassA의 자료형이 자료형A인지 확인해 주는 예약어
Animal hAnimal=new Human();
if(hAnimal instanceof Human){
Human hunam=(Human)hAnimal; //hAnimal Downcasting to Human
}
by doing down casting can use method which does not exist in parent class
AnimalTest.java
package polymorphism;
import java.util.ArrayList;
class Animal{
public void move() {
System.out.println(" .");
}
}
class Human extends Animal{
public void move() {
System.out.println(" .");
}
public void readBook() {
System.out.println(" .");
}
}
class Tiger extends Animal{
public void move() {
System.out.println(" .");
}
public void hunting() {
System.out.println(" .");
}
}
class Eagle extends Animal{
public void move() {
System.out.println(" .");
}
public void flying() {
System.out.println(" .");
}
}
public class AnimalTest {
ArrayList<Animal> aniList=new ArrayList<Animal>();
public static void main(String[] args) {
AnimalTest aTest=new AnimalTest();
aTest.addAnimal();
System.out.println(" ");
aTest.testCasting();
}
public void addAnimal() {
aniList.add(new Human());
aniList.add(new Tiger());
aniList.add(new Eagle());
for(Animal ani:aniList) {
ani.move();
}
}
public void testCasting() {
for(int i=0;i<aniList.size();i++) {
Animal ani=aniList.get(i);
if(ani instanceof Human) {
Human h=(Human)ani;
h.readBook();
}
else if(ani instanceof Tiger) {
Tiger t=(Tiger)ani;
t.hunting();
}
else if(ani instanceof Eagle) {
Eagle e=(Eagle)ani;
e.flying();
}
else {
System.out.println(" .");
}
}
}
}